// pages/login/login.ts
Page({
  data: {
    username: '',
    password: ''
  },
  onLoad() {},
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {},

  onUserNameInput(e: WechatMiniprogram.Input) {
    this.setData({
      username: e.detail.value
    })
  },
  onPasswordInput(e: WechatMiniprogram.Input) {
    this.setData({
      password: e.detail.value
    })
  },

  login() {
    if (!this.data.username || !this.data.password) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: 'https://8.130.135.229:8080/api/user/login',
      method: 'POST',
      data: {
        username: this.data.username,
        password: this.data.password
      },
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult) => {
        const response = res.data as { code: number; data: { id: string }; message: string }
        if (response.code === 200) {
          wx.setStorageSync('userId', response.data.id)
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          })
          wx.navigateTo({
            url: '/pages/profile/profile'
          })
        } else {
          wx.showToast({
            title: response.message,
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  toRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    })
  }
})